package main

import (
	"flag"
	"fmt"
	"github.com/golang/glog"
	"io"
	"log"
	"net/http"
	"runtime"
)

// 运行时加上参数: --v=2 --logtostderr=true
func main()  {
	flag.Parse()

	glog.V(2).Info("Starting HttpServer ...")

	mux := http.NewServeMux()
	mux.HandleFunc("/", rootHandler)
	mux.HandleFunc("/healthz", healthz)
	err := http.ListenAndServe(":80", mux)

	if err!=nil {
		log.Fatal(err)
	}
}

func healthz(writer http.ResponseWriter, request *http.Request) {
	fmt.Println("healthz ...")

	setRequestHeadersToResponse(writer, request)
	setVariablesToResponse(writer, request)
	logClientInfo(writer, request)

	io.WriteString(writer, "200")
}

func rootHandler(writer http.ResponseWriter, request *http.Request) {
	fmt.Println("handle root ...")

	setRequestHeadersToResponse(writer, request)
	setVariablesToResponse(writer, request)
	logClientInfo(writer, request)
}

func setRequestHeadersToResponse(writer http.ResponseWriter, request *http.Request)  {
	for k, values := range request.Header{
		fmt.Printf("key:%s, value:%s\n", k, values)
		for _, v := range values{
			writer.Header().Add(k, v)
		}
	}
}

func setVariablesToResponse(writer http.ResponseWriter, request *http.Request)  {
	writer.Header().Add("Go-Version", runtime.Version())
}

func logClientInfo(writer http.ResponseWriter, request *http.Request)  {
	glog.V(2).Info("RemoteAddr:", request.RemoteAddr)
	glog.V(2).Info("Status-Code:", "200")
}
